package org.west.sky.frame.activiti.study.chapter14;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.west.sky.frame.activiti.study.chapter14.demo0302.CostCalculation;
import org.west.sky.frame.activiti.study.util.ActivitiEngineUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author: chz
 * date: 2025/3/12
 * description: 脚本任务
 */
public class RunDemo14_3 extends ActivitiEngineUtil {

    public static void main(String[] args) {
        RunDemo14_3 runDemo13_1_1 = new RunDemo14_3();
        runDemo13_1_1.deploy();
    }

    @SneakyThrows
    private void deploy() {
        loadActivitiConfigAndInitEngine("activiti.drools.xml");
        //部署流程
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource("processes/chapter14/Chapter14_3.bpmn20.xml")
                .addClasspathResource("rules/Chapter14_3.drl")
                .deploy();

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();

        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());

        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        CostCalculation myCostCalculation = new CostCalculation();
        myCostCalculation.setOriginalPrice(6000);
        Map<String, Object> variables = new HashMap<>();
        variables.put("myCostCalculation", myCostCalculation);
        taskService.complete(task.getId(), variables);

        List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).list();
        list.forEach(item -> {
            System.out.println("====变量：" + item.getVariableName() + "的值为：" + JSON.toJSONString(item.getValue()));
        });
        closeEngine();
    }


}
